//
//  SmscodeLogic.swift
//  Casecord
//
//  Created by baozi on 2024/1/4.
//

import Foundation
import RxSwift
class SmscodeLogic: BaseLogic {
    @Published var otp: String = ""
    @Published var isSending: Bool = false
    @Published var isLogining: Bool = false
    @Published var countdownSeconds: Int = 0
    var areaCode: String = ""
    var phone: String = ""
    var password: String?
    var signType: SignType = .password_set
    
    
    func login() {
        if isLogining {
            return
        }
        isLogining = true
        
        LoginAPI
            .login(
                loginFrom: signType == .password_set ? .type_regiter_1 : .type_sms_code_4,
                loginType: .type_phone_0,
                areaCode: areaCode,
                phoneNumber: phone,
                password: password,
                smsCode: otp,
                apiId: nil,
                apiToken: nil
            )
            .make()
            .subscribe(onSuccess: { [weak self] res in
                guard let self = self else { return }
                Task {
                    await UserService.shared.login(res)
                }
            }, onDisposed: { [weak self] in
                self?.isLogining = false
            })
            .disposed(by: disposeBag)
    }
    
    
    func reSendSMS() {
        guard isSending == false else {
            PPLog("发送中...")
            return
        }
        isSending = true
        
        LoginAPI
            .smsSend(
                areaCode: areaCode,
                phone: phone,
                smsType: "LOGIN"
            )
            .make()
            .subscribe(onSuccess: { [weak self] res in
                guard let self = self else { return }
                self.isSending = true
                self.startTimer()
            })
            .disposed(by: disposeBag)
    }
    
    func startTimer() {
        isSending = true
        CountDown
            .timer(count: 60)
            .subscribe(on: MainScheduler.asyncInstance)
            .subscribe { [weak self] (isStop: Bool, leftTime: CGFloat) in
                guard let self = self else { return }
                if isStop {
                    self.isSending = false
                } else {
                    self.countdownSeconds = leftTime.floor
                }
            }
            .disposed(by: self.disposeBag)
    }
}
